package api

import (
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"api/pkg"
	"common/consulinit"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
	user "user_srv/proto"
)

var (
	userAddress = "127.0.0.1:50051"
	userServer  = flag.String("user", userAddress, "The server address")
	userSrv     = handler.ServerNewClient().UserServer(userServer)
)

func RegisterUser() {
	registration := consulinit.ServiceRegistration{
		Name:    "user_srv",
		Address: "117.27.231.112",
		Port:    50051,
		Tags:    nil,
	}
	consulinit.RegisterService(registration)
}

func Register(c *gin.Context) {
	RegisterUser()
	var json *request.Register
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Register(c, &user.RegisterRequest{
		Username: json.Username,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "注册成功", register)
}

func Login(c *gin.Context) {
	RegisterUser()
	var json *request.Login
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Login(c, &user.LoginRequest{
		Username: json.Username,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	tokenHandler, _ := pkg.TokenHandler(strconv.FormatInt(register.Id, 10))
	response.Response(c, 200, "登录成功", tokenHandler)
}
